from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session

from ..crud.item import (
    create_item,
    delete_item,
    get_item,
    get_items,
    get_total_items,
    update_item,
)
from ..db.session import get_db
from ..exceptions.custom_exceptions import NotFoundException
from ..schemas.item import ItemCreate, ItemOut, ItemUpdate
from ..utils.response import APIResponse

router = APIRouter(tags=["items"])

# 模块级单例：预先创建 Depends 实例
get_db_dependency = Depends(get_db)


@router.post("/", response_model=APIResponse)
def create_item_route(item: ItemCreate, db: Session = get_db_dependency):
    db_item = create_item(db, item)
    return APIResponse.ok(ItemOut.model_validate(db_item).model_dump(), "Item created")


@router.get("/", response_model=APIResponse)
def read_items(skip: int = 0, limit: int = 100, db: Session = get_db_dependency):
    items = get_items(db, skip=skip, limit=limit)
    return APIResponse.ok(
        [ItemOut.model_validate(i).model_dump() for i in items],
        "Items retrieved",
    )


@router.get("/page", response_model=APIResponse)
def read_items_paginated(
    page: int = Query(1, ge=1, description="页码，从 1 开始"),
    size: int = Query(10, ge=1, le=100, description="每页大小"),
    db: Session = get_db_dependency,
):
    """新增：分页查询项（使用 page/size 参数，返回元数据）"""
    skip = (page - 1) * size
    items = get_items(db, skip=skip, limit=size)
    total = get_total_items(db)  # 获取总项数

    # 结构化分页数据
    paginated_data = {
        "items": [ItemOut.model_validate(i).model_dump() for i in items],
        "total": total,
        "page": page,
        "size": size,
        "total_pages": (total + size - 1) // size,  # 向上取整
    }

    return APIResponse.ok(
        paginated_data,
    )


@router.get("/{item_id}", response_model=APIResponse)
def read_item(item_id: int, db: Session = get_db_dependency):
    db_item = get_item(db, item_id)
    if not db_item:
        raise NotFoundException(name="Item")
    return APIResponse.ok(
        ItemOut.model_validate(db_item).model_dump(), "Item retrieved"
    )


@router.put("/{item_id}", response_model=APIResponse)
def update_item_route(item_id: int, item: ItemUpdate, db: Session = get_db_dependency):
    db_item = update_item(db, item_id, item)
    if not db_item:
        raise NotFoundException(name="Item")
    return APIResponse.ok(
        ItemOut.model_validate(db_item).model_dump(),
        "Item updated",
    )


@router.delete("/{item_id}", response_model=APIResponse)
def delete_item_route(item_id: int, db: Session = get_db_dependency):
    db_item = delete_item(db, item_id)
    if not db_item:
        raise NotFoundException(name="Item")
    return APIResponse.ok(None, "Item deleted")
